package com.yanq.liancar.activity;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxtool.view.RxToast;
import com.yanq.liancar.R;
import com.yanq.liancar.activity.base.BaseToolbarActivity;
import com.yanq.liancar.adapter.DialogAdapter;
import com.yanq.liancar.adapter.DialogAdapter1;
import com.yanq.liancar.adapter.NewUserAdapter;
import com.yanq.liancar.base.BaseLYFragment;
import com.yanq.liancar.base.BaseLazyFragment;
import com.yanq.liancar.bean.BaseBean;
import com.yanq.liancar.bean.NewUserBean;
import com.yanq.liancar.bean.NoScrollViewPager;
import com.yanq.liancar.bean.SignInBean;
import com.yanq.liancar.bean.SignInListBean;
import com.yanq.liancar.bean.UserBean;
import com.yanq.liancar.fragment.FindFragment;
import com.yanq.liancar.fragment.GuanjiaFragment;
import com.yanq.liancar.fragment.HomeFragment;
import com.yanq.liancar.fragment.MarketFragment;
import com.yanq.liancar.fragment.MineFragment;
import com.yanq.liancar.url.Config;
import com.yanq.liancar.util.LogUtils;
import com.yanq.liancar.util.Utils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MinUserMainActivity extends BaseToolbarActivity implements View.OnClickListener {

    @BindView(R.id.viewPager)
    NoScrollViewPager viewPager;
    @BindView(R.id.home)
    RadioButton home;
    @BindView(R.id.find)
    RadioButton find;
    @BindView(R.id.guanjia)
    RadioButton guanjia;
    @BindView(R.id.market)
    RadioButton market;
    @BindView(R.id.mine)
    RadioButton mine;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    private List<BaseLazyFragment> fragments = new ArrayList<>();
    private int type;
    private String lastTime;  //上次签到时间
    private int siginNum;  //连续签到次数
    private List<String> dateList = new ArrayList<>(); //连续签到日期
    private NewUserAdapter mNewUserAdapter;
    private List<NewUserBean.DataBean> mList=new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_minusermain);
        ImmersionBar.with(this).statusBarDarkFont(true).init();
        ButterKnife.bind(this);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);  //底部向上
        //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);//顶部向下
        // mImmersionBar = ImmersionBar.with(this);

        home.setOnClickListener(this);
        find.setOnClickListener(this);
        guanjia.setOnClickListener(this);
        market.setOnClickListener(this);
        mine.setOnClickListener(this);
        type = getIntent().getIntExtra("type", 0);
        LogUtils.e("sdada", type + "");
        viewPager.setScroll(false);

        viewPager.setPageMargin(getResources().getDimensionPixelOffset(R.dimen.dp_5));
        viewPager.setOffscreenPageLimit(5);

        HomeFragment homeFragment = new HomeFragment();
        GuanjiaFragment guanjiaFragment = new GuanjiaFragment();
        FindFragment findFragment = new FindFragment();
        MarketFragment marketFragment = new MarketFragment();
        MineFragment mineFragment = new MineFragment();
        fragments.add(homeFragment);
        fragments.add(findFragment);
        fragments.add(guanjiaFragment);
        fragments.add(marketFragment);
        fragments.add(mineFragment);

        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        });
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                setCurrent(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });

        setCurrent(0);
        go();

//        if (!TextUtils.isEmpty(UserBean.getcToken(this))) {
//            getLastTime();
//        }
        getSignIn();
        getCoupon();
    }


    private void go() {
        if (type == 4) {
            viewPager.setCurrentItem(4);
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home:
                viewPager.setCurrentItem(0, false);
                break;
            case R.id.find:
                viewPager.setCurrentItem(1, false);
                break;
            case R.id.guanjia:
                viewPager.setCurrentItem(2, false);
                break;
            case R.id.market:
                viewPager.setCurrentItem(3, false);
                break;
            case R.id.mine:
                viewPager.setCurrentItem(4, false);
                break;
        }

    }

    public void setCurrent(int id) {
        switch (id) {
            case 0:
                radioGroup.check(R.id.home);
                //Utils.setStatusTextColor(true, this);
                break;
            case 1:
                radioGroup.check(R.id.find);
                //Utils.setStatusTextColor(true, this);
                break;
            case 2:
                radioGroup.check(R.id.guanjia);
                //Utils.setStatusTextColor(true, this);
                break;
            case 3:
                radioGroup.check(R.id.market);
                //Utils.setStatusTextColor(true, this);
                break;
            case 4:
                radioGroup.check(R.id.mine);
                //Utils.setStatusTextColor(false, this);
                break;
        }

    }


    //签到
    private void SignIn() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date(System.currentTimeMillis());
        final String str = simpleDateFormat.format(date);
        LogUtils.e("111111111", str);

        if (!str.equals(lastTime)) {
            signInDialog();
        }

    }

    //签到弹窗
    private void signInDialog() {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        View contentView = LayoutInflater.from(this).inflate(R.layout.qiandao_dialog, null);
        alertDialog.setView(contentView);
        alertDialog.setCancelable(false);
        alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        alertDialog.show();

        TextView tv_numDay = contentView.findViewById(R.id.tv_numDay);
        tv_numDay.setText(siginNum + "");
        TextView tv_qiandao = contentView.findViewById(R.id.tv_qiandao);
        ImageView tv_Close = contentView.findViewById(R.id.img_Close);

        tv_Close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

        tv_qiandao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //调用签到接口，成功回调后保存当前时

                OkGo.<String>get(Config.s + "llc/toSign")
                        .tag(this)
                        .params("token", UserBean.getcToken(MinUserMainActivity.this))
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                LogUtils.e("签到接口", response.body());
                                Gson gson = new Gson();
                                SignInBean info = gson.fromJson(response.body(), SignInBean.class);
                                if (info.isIsSuccess()) {
                                    signInSuccDialog(info.getData().getSignintegral() + "");
                                    addIntegral(info.getData().getSignintegral());
                                } else {
                                    RxToast.error(info.getOutputMessage());
                                }
                            }
                        });
                alertDialog.dismiss();
            }
        });
    }

    //添加积分，同步到后台
    private void addIntegral(int  jifen) {
        //获取上次签到时间与连续签到次数
        OkGo.<String>get("http://llc.value19.com/jifen.php")
                .tag(this)
                .params("type", 2)
                .params("apid", UserBean.getcToken(MinUserMainActivity.this))
                .params("name", UserBean.getName(MinUserMainActivity.this))
                .params("jifen",  jifen)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        //                        SignInBean info = gson.fromJson(response.body(), SignInBean.class);
                        //                        if (info.isIsSuccess()) {
                        //                            if (null != info.getData().getLastSignDate() && !TextUtils.isEmpty(info.getData().getLastSignDate())) {
                        //                                lastTime = info.getData().getLastSignDate().substring(0, 10);
                        //                            }
                        //                            siginNum = info.getData().getSignNum();
                        //                            LogUtils.e("上次签到时间：", lastTime + "====" + siginNum);
                        //                            SignIn();
                        //                        } else {
                        //                            RxToast.error(info.getOutputMessage());
                        //                        }
                    }
                });
    }

    //签到成功
    private void signInSuccDialog(String jifen) {
        final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
        View contentView = LayoutInflater.from(this).inflate(R.layout.qiandao_succ_dialog, null);
        alertDialog.setView(contentView);
        alertDialog.setCancelable(false);
        alertDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        alertDialog.show();

        TextView tv_qiandao_succ = contentView.findViewById(R.id.tv_qiandao_succ);
        TextView tv_jifen = contentView.findViewById(R.id.tv_jifen);
        ImageView tv_Close = contentView.findViewById(R.id.img_Close);

        tv_Close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });

        tv_jifen.setText(jifen);

        tv_qiandao_succ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putStringArrayList("dateList", (ArrayList<String>) dateList);
                RxActivityTool.skipActivity(MinUserMainActivity.this, SigInRecordActivity.class, bundle);
                alertDialog.dismiss();
            }
        });
    }

    private void getLastTime() {
        //获取上次签到时间与连续签到次数
        OkGo.<String>get(Config.s + "llc/getLastSignMsg")
                .tag(this)
                .params("token", UserBean.getcToken(MinUserMainActivity.this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        SignInBean info = gson.fromJson(response.body(), SignInBean.class);
                        if (info.isIsSuccess()) {
                            if (null != info.getData().getLastSignDate() && !TextUtils.isEmpty(info.getData().getLastSignDate())) {
                                lastTime = info.getData().getLastSignDate().substring(0, 10);
                            }
                            siginNum = info.getData().getSignNum();
                            LogUtils.e("上次签到时间：", lastTime + "====" + siginNum);
                            SignIn();
                        } else {
                            //RxToast.info(info.getOutputMessage());
                        }
                    }
                });
    }

    //获取连续签到日期
    private void getSignIn() {
        OkGo.<String>get(Config.s + "llc/querySignRecord")
                .tag(this)
                .params("token", UserBean.getcToken(this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        SignInListBean bean = gson.fromJson(response.body(), SignInListBean.class);
                        if (bean.isIsSuccess()) {
                            dateList.clear();
                            dateList.addAll(bean.getData());
                        } else {
                           // RxToast.info(bean.getOutputMessage());
                        }
                    }

                });
    }

    //判断是否为新用户（首次登陆领取优惠券）
    private void getCoupon() {
        //获取上次签到时间与连续签到次数
        OkGo.<String>post(Config.s + "llc/SerPackageController/Servicequan")
                .tag(this)
                .params("token", UserBean.getcToken(MinUserMainActivity.this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        NewUserBean info = gson.fromJson(response.body(), NewUserBean.class);
                        if (info.getCode()==200) {
                          mList.clear();
                          mList.addAll(info.getData());
                            myDialog(mList);
                        } else if (info.getCode()==400){
                            //是否弹出签到窗口
                            getLastTime();
                        }else {
                           // RxToast.info(info.getOutputMessage());
                        }
                    }
                });
    }

    //确定领取优惠券
    private void getReceive() {
        //获取上次签到时间与连续签到次数
        OkGo.<String>post(Config.s + "llc/SerPackageController/subservice")
                .tag(this)
                .params("token", UserBean.getcToken(MinUserMainActivity.this))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Gson gson = new Gson();
                        BaseBean baseBean = gson.fromJson(response.body(), BaseBean.class);
                        if (baseBean.isIsSuccess()) {
                          RxToast.success(baseBean.getOutputMessage());
                        } else {
                            //RxToast.info(baseBean.getOutputMessage());
                        }
                    }
                });
    }


    private void myDialog( List<NewUserBean.DataBean> mList ) {
        final Dialog bottomDialog = new Dialog(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_newuser, null);
        bottomDialog.setContentView(contentView);
        ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) contentView.getLayoutParams();
        params.width = getResources().getDisplayMetrics().widthPixels-200;
        contentView.setLayoutParams(params);
        bottomDialog.getWindow().setGravity(Gravity.CENTER);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation2);
        bottomDialog.setCanceledOnTouchOutside(false);
        bottomDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        bottomDialog.show();

        TextView tv_Receive=bottomDialog.findViewById(R.id.tv_Receive);
        tv_Receive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomDialog.dismiss();
                //getReceive();
                //领取完优惠券，弹出签到窗口
                getLastTime();

            }
        });
        final RecyclerView dialog_recyclerView = bottomDialog.findViewById(R.id.recyclerview);
        dialog_recyclerView.setNestedScrollingEnabled(false);
        dialog_recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mNewUserAdapter = new NewUserAdapter(R.layout.dialog_newuser_item, mList);
        dialog_recyclerView.setAdapter(mNewUserAdapter);
    }
}
